package hhm.android.library.netWorkState

import android.app.Application
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build

object NetworkUtils {
    fun isNetworkAvailable(application: Application): Boolean {
        val connMgr =
            application.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //高版本使用NetworkCapabilities来判断有无网络
            val networkCapabilities = connMgr.getNetworkCapabilities(connMgr.activeNetwork)
            networkCapabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
                ?: false
        } else {
            //低版本直接使用networkInfo
            val networkInfo = connMgr.activeNetworkInfo
            networkInfo?.isConnected ?: false
        }
    }
}